import { ref } from 'vue'

export default function useMiddleInteractive () {
  const currentShow = ref('cd')
  const middleLStyle = ref(null)
  const middleRStyle = ref(null)
  const touch = {}
  let currentView = 'cd'
  const onMiddleTouchStart = (e) => {
    touch.startX = e.touches[0].pageX
  }
  const onMiddleTouchMove = (e) => {
    const deltaX = e.touches[0].pageX - touch.startX
    // 视图的初始偏移量
    // 歌词视图显示在屏幕时，唱片位于屏幕左侧
    const left = currentView === 'cd' ? 0 : -window.innerWidth
    // offsetWidth:0 视图无偏移
    // offsetWidth:-window.innerWidth 视图往左偏移
    // offsetWidth -window.innerWidth ~ 0 视图正在滑动
    const offsetWidth = Math.min(
      0,
      Math.max(left + deltaX, -window.innerWidth)
    )
    touch.percent = Math.abs(offsetWidth / window.innerWidth)
    if (currentView === 'cd') {
      // 滑动偏移量>20%切换到歌词 用户比较容易切换到歌词
      currentShow.value = touch.percent > 0.2 ? 'lyric' : 'cd'
    } else {
      // 滑动偏移量>80%切换到唱片 用户滑动较长距离才切换到唱片，避免误操作
      // 滑动偏移量越大，touch.percent越小
      currentShow.value = touch.percent < 0.8 ? 'cd' : 'lyric'
    }
    middleLStyle.value = { opacity: 1 - touch.percent }
    middleRStyle.value = { transform: `translateX(${offsetWidth}px)` }
  }
  const onMiddleTouchEnd = () => {
    let offsetWidth
    let opacity
    if (currentShow.value === 'cd') {
      currentView = 'cd'
      offsetWidth = 0
      opacity = 1
    } else {
      currentView = 'lyric'
      // 向左移动375px，参照点为元素自身左上角
      offsetWidth = -window.innerWidth
      opacity = 0
    }
    const duration = 1000
    middleLStyle.value = {
      opacity,
      transition: `all ${duration}ms`
    }
    middleRStyle.value = {
      transform: `translateX(${offsetWidth}px)`,
      transition: `all ${duration}ms`
    }
  }
  return {
    currentShow,
    middleLStyle,
    middleRStyle,
    onMiddleTouchStart,
    onMiddleTouchMove,
    onMiddleTouchEnd
  }
}
